#ifndef _WEATHER_H

int getDirectionValue(String s)
{
  if (s.length() >= 2)
  {
    String x = s.substring(0, 2); // 提取前两位数据
    if (x == "N")
    {
      return 0; // 正北方向
    }
    else if (x == "NE")
    {
      return 1; // 东北方向
    }
    else if (x == "E")
    {
      return 2; // 正东方向
    }
    else if (x == "SE")
    {
      return 3; // 东南方向
    }
    else if (x == "S")
    {
      return 4; // 正南方向
    }
    else if (x == "SW")
    {
      return 5; // 西南方向
    }
    else if (x == "W")
    {
      return 6; // 正西方向
    }
    else if (x == "NW")
    {
      return 7; // 西北方向
    }
  }
  else if (s.length() == 1)
  {
    String x = s.substring(0, 1); // 提取前一位数据
    if (x == "N")
    {
      return 0; // 正北方向
    }
    else if (x == "E")
    {
      return 2; // 正东方向
    }
    else if (x == "S")
    {
      return 4; // 正南方向
    }
    else if (x == "W")
    {
      return 6; // 正西方向
    }
  }

  return -1; // 无效的方向，返回错误码
}

bool getweainfo()
{
  uint8_t i = 0;
  if (forecast.update())
  {
    for (i = 0; i < 3; i++)
    {
      wea[i].code_day = forecast.getDayCode(i);
      wea[i].code_night = forecast.getNightCode(i);
      wea[i].wind_direction = getDirectionValue(forecast.getWindDirection(i));
      wea[i].high = forecast.getHigh(i);
      wea[i].low = forecast.getLow(i);
      wea[i].rain = forecast.getRain(i);
      wea[i].wind_scale = forecast.getWindScale(i);

      // 创建文件
      String FS_MOUNT_POINT;
      // 上电后读取复位前的数据
      switch (i)
      {
      case 0:
        FS_MOUNT_POINT = "/data0";
        break;
      case 1:
        FS_MOUNT_POINT = "/data1";
        break;
      case 2:
        FS_MOUNT_POINT = "/data2";
        break;
      }
      File file = SPIFFS.open(FS_MOUNT_POINT+ "/data.txt", "w");

      if (!file)
      {
        Serial.println("无法创建文件！");
      }
      // 将变量的值写入文件
      file.println(String(wea[i].code_day));
      file.println(String(wea[i].code_night));
      file.println(String(wea[i].wind_direction));
      file.println(String(wea[i].high));
      file.println(String(wea[i].low));
      file.println(String(wea[i].rain));
      file.println(String(wea[i].wind_scale));

      // 关闭文件
      file.close();
      Serial.println("数据已成功写入文件！");

      Serial.printf("========Day%d========\n", i);
      Serial.printf("Day Weather:%d\n ", wea[i].code_day);
      Serial.printf("Night Weather:%d\n", wea[i].code_night);
      // tempreture
      Serial.printf("High:%d°C\n", wea[i].high);
      Serial.printf("Low:%d°C\n", wea[i].low);

      Serial.printf("Rainfall:%d %\n ", wea[i].rain);
      Serial.printf("Wind Direction:%d\n ", wea[i].wind_direction);
      Serial.printf("Wind Scale:%d\n", wea[i].wind_scale);
    }
  }
  else
  {
    return false;
  }
  return true;
}

#endif